const request = require('request');
const fs = require('fs');


Date.prototype.format = function(fmt)   
{ //author: meizz   
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日   
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}

function promiseRequest(json) {

  const options = {
    url: 'http://api.waditu.com',
    method: 'POST',
    json: json
  };

  return new Promise(function (resolve, reject) {
    request(options, function (err, res, body) {
      if (err) {
        return reject(err);
      } else if (res.statusCode !== 200) {
        err = new Error("Unexpected status code: " + res.statusCode);
        err.res = res;
        return reject(err);
      }
      resolve(body);
    });
  });
}


function writeFile(json, filePath) {
  try {
    // fs.writeFile(filePath, JSON.stringify(json, null, 4),
    //   function (err) {
    //     if (err) {
    //       console.log(filePath + "文件写入失败")
    //     } else {
    //       console.log(filePath + "文件写入成功");
    //     }
    //   })
    fs.writeFileSync(filePath, JSON.stringify(json, null, 4))
    console.log(filePath + "文件写入成功");
  } catch (e) {
    console.log(e);
  }
}


; (async () => {

  let cal = JSON.parse(fs.readFileSync('trade_cal.json'));
  
  if (!fs.existsSync('dailys') ) {
    fs.mkdirSync('dailys')
  }
  
  // for (let index = 0; index < 10; index++) {
  for (let index = 0; index < cal.length; index++) {
    const element = cal[index];
    if (element[1] == 1) {
      let end = false;
      var time2 = new Date().format("yyyyMMdd");  

      if (element[0] == time2) {
        end = true;
      }

      var filePath = 'dailys/' + element[0] + '.json'
      if (fs.existsSync(filePath) ) {
        console.log('exists skip. ' , element[0]);
        if (end) {
          console.log(time2 + ' end');
          break;
        }
        continue;
      }
      console.log(element);

      // 每天行情
      const dest = {
        "api_name": "daily",
        "token": "0affa53db2b6d3ec6b09ff30fde78f232dc168336a05767f7fa98a63",
        "params": { "trade_date": element[0] },
        "fields": "ts_code,pct_chg,vol,close"
      }

      var body = await promiseRequest(dest)
     
      
      if (!!body && body.code == 0 && !!body.data.items && body.data.items.length > 0) {
        writeFile(body.data.items, filePath)
      }

      if (end) {
        console.log(time2 + ' end');
        break;
      }

    }
  }

})()
